A nested while loop is a while loop that is placed inside another while loop. It allows repeatedly executing a set of code within the outer loop and, for each iteration of the outer loop, executing the inner loop multiple times.
Here's a C program demonstrating a nested while loop with comments:
#include <stdio.h>
int main() {
int outer_count = 1; // Initialize the outer loop counter
while (outer_count <= 3) { // Outer loop runs 3 times
printf("Outer loop iteration: %d\n", outer_count);
int inner_count = 1; // Initialize the inner loop counter
while (inner_count <= 4) { // Inner loop runs 4 times
printf("Inner loop iteration: %d\n", inner_count);
inner_count++; // Increment the inner loop counter
}
outer_count++; // Increment the outer loop counter
}
return 0;
}
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
In the output, the iterations of both the outer loop and the inner loop. The inner loop runs four times for each iteration of the outer loop, demonstrating the nested behaviour of the while loops.
What is a nested while loop in C?
What does a nested while loop contain?
What is the purpose of using nested while loops in C?